package cn.ryh.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用NIO读取文件内容
 */
public class NIOReadFile {
    public static void main(String[] args) throws IOException{
        FileInputStream fis = null;
        FileChannel fic = null;
        FileOutputStream fos =null;
        FileChannel foc = null;

        try {
            fis = new FileInputStream("src\\main\\cn\\ryh\\nio\\NIO简介.txt");
            //获取通道
            fic = fis.getChannel();

            fos = new FileOutputStream("readmeCopy.txt");
            foc = fos.getChannel();
            //创建缓冲区
            ByteBuffer bybf = ByteBuffer.allocate(1024);
            //使用通道从缓冲区中读取内容

            while (fic.read(bybf) > 0 ){
                bybf.flip();
                foc.write(bybf);
                bybf.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            if (null != fic) {
                fic.close();
            }
            if (null != foc) {
                foc.close();
            }
            if (null != fis) {
                fis.close();
            }
            if (null != fos) {
                fos.close();
            }
        }
    }
}
